<template>
    <section>
        <el-dialog
                :title="ground.id == 0 ? '添加土地' : '编辑土地' "
                :visible.sync="visible"
                :value="value"
                @close="close"
                width="900px"
        >
            <el-form
                    :model="ground"
                    :inline="true"
                    :rules="rules"
                    ref="groundForm"
            >
                <el-form-item
                        label="土地编号"
                        :label-width="labelWidth"
                        prop="groundCode"
                >
                    <el-input
                            v-model="ground.groundCode"
                            auto-complete="off"
                            maxlength="32"
                            suffix-icon="fa fa-barcode"
                            placeholder="请填写土地编号"
                    />
                </el-form-item>
                <el-form-item
                        label="名称"
                        :label-width="labelWidth"
                        prop="name"
                >
                    <el-input
                            v-model="ground.name"
                            auto-complete="off"
                            maxlength="32"
                            suffix-icon="fa fa-vcard"
                            placeholder="请填写果园名称"
                    />
                </el-form-item>
                <el-form-item
                        label="面积"
                        :label-width="labelWidth"
                        prop="acreage"
                >
                    <el-input
                            v-model="ground.acreage"
                            auto-complete="off"
                            maxlength="11"
                            suffix-icon="fa fa-ils"
                            placeholder="请填写土地面积(㎡)"
                    />
                </el-form-item>
                <el-form-item
                        label="附属地面积"
                        :label-width="labelWidth"
                        prop="attachedArea"
                >
                    <el-input
                            v-model="ground.attachedArea"
                            auto-complete="off"
                            maxlength="11"
                            suffix-icon="fa fa-ils"
                            placeholder="请填写附属地面积(㎡)"
                    />
                </el-form-item>

                <el-form-item
                        label="授粉树品种"
                        :label-width="labelWidth"
                        prop="pollinationTreeType"
                >
                    <el-select
                            v-model="ground.pollinationTreeType"
                            placeholder="请选择授粉树品种"
                    >
                        <el-option
                                v-for="item in pollinationTreeTypes"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item
                        label="地块从属"
                        :label-width="labelWidth"
                        prop="attributionType"
                >
                    <el-select
                            v-model="ground.attributionType"
                            placeholder="请选择地块从属"
                    >
                        <el-option
                                v-for="item in ownTypes"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item
                        label="合作社"
                        :label-width="labelWidth"
                        prop="cooperativeId" v-if="userId===0"
                >
                    <el-select
                            v-model="ground.cooperativeId"
                            placeholder="请选择合作社"
                            @change="cooperativeChange"
                    >
                        <el-option
                                v-for="item in cooperatives"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="userId===0"
                              label="农户"
                              :label-width="labelWidth"
                              prop="farmerId"
                >
                    <el-select
                            v-model="ground.farmerId"
                            placeholder="请选择农户"
                    >
                        <el-option
                                v-for="item in farmers"
                                :key="item.userId"
                                :label="item.name"
                                :value="item.userId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item
                        label="是否有防冰雹网"
                        :label-width="labelWidth"
                        prop="protectHailNet"
                >
                    <div style="width: 199px">
                        <el-switch
                                v-model="ground.protectHailNet"
                                active-color="#13ce66"
                        >
                        </el-switch>
                    </div>
                </el-form-item>
                <el-form-item
                        label="是否是基本农田"
                        :label-width="labelWidth"
                        prop="farmlandFlag"
                >
                    <div style="width: 199px">
                        <el-switch
                                v-model="ground.farmlandFlag"
                                active-color="#13ce66"
                        >
                        </el-switch>
                    </div>
                </el-form-item>
                <el-form-item label="联系地址"
                              :label-width="labelWidth"
                              prop="address">
                    <el-cascader
                            :options="areas"
                            v-model="area"
                            placeholder="请选择区域信息"
                            @active-item-change="areaChange"
                            :props="areaProps"
                    ></el-cascader>
                    <el-input
                            v-model="ground.address"
                            auto-complete="off"
                            maxlength="128"
                            suffix-icon="fa fa-map-marker"
                            placeholder="请填写详细地址"
                    />
                </el-form-item>
                <el-form-item
                        label="用途"
                        :label-width="labelWidth"
                        prop="purpose"
                >
                    <el-input
                            type="textarea"
                            v-model="ground.purpose"
                            auto-complete="off"
                            maxlength="128"
                            suffix-icon="fa fa-mobile"
                            placeholder="请填写用途"
                    />
                </el-form-item>
            </el-form>
            <span
                    slot="footer"
                    class="dialog-footer"
            >
        <el-button
                size="small"
                @click="cancle('groundForm')"
        >取 消</el-button>
        <el-button
                size="small"
                type="primary"
                @click="submit('groundForm')"
        >确 定</el-button>
      </span>
        </el-dialog>
    </section>
</template>
<style>
</style>
<script>
    import {mapState} from "vuex";

    export default {
        name: "AddAndEdit",
        data() {
            var validAddress = (rule, value, callback) => {
                if (this.area.length < 5) {
                    callback(new Error("请选择联系地址的区域信息"));
                } else if (!value) {
                    callback(new Error("请填写详细地址"));
                } else {
                    callback();
                }
            };
            return {
                visible: false,
                labelWidth: "200px",
                pollinationTreeTypes: [],
                ownTypes: [],
                cooperatives: [],
                userId: 0,
                areas: [],
                area: [],
                farmers: [],
                ground: {
                    id: 0,
                    groundCode: "",
                    name: "",
                    farmerId: '',
                    acreage: '',
                    protectHailNet: '',
                    pollinationTreeType: '',
                    purpose: '种植业',
                    farmlandFlag: '',
                    attachedArea: '',
                    cooperativeId: '',
                    attributionType: '',
                    address: ''
                },
                options: [{code: true, name: "是"}, {code: false, name: '否'}],
                rules: {
                    groundCode: [{required: true, message: "请输入土地编号", trigger: "blur"}],
                    name: [{required: true, message: "请输入名称", trigger: "blur"}],
                    acreage: [{required: true, validator: this.$validator.decimalValid, trigger: "blur"}],
                    protectHailNet: [{required: true, message: "请选择是否有防冰雹网", trigger: "blur"}],
                    attachedArea: [{required: true, validator: this.$validator.decimalValid, trigger: "blur"}],
                    pollinationTreeType: [{required: true, message: "请选择授粉树品种", trigger: "blur"}],
                    farmlandFlag: [{required: true, message: "请选择是否是基本农田", trigger: "blur"}],
                    farmerId: [{required: true, message: "请选择农户", trigger: "blur"}],
                    cooperativeId: [{required: true, message: "请选择农户", trigger: "blur"}],
                    attributionType: [{required: true, message: "请选择地块从属", trigger: "blur"}],
                    address: [{required: true, validator: validAddress, trigger: "blur"}]
                },
                areaProps: {
                    value: 'value',
                    label: 'label',
                    children: 'children'
                }
            };
        },
        computed: {
            ...mapState({
                codebooks: state => state.codebooks.codebooks
            })
        },
        watch: {
            value: {
                deep: true,
                immediate: true,
                handler: function (val) {
                    this.visible = val.show;
                    this.labelWidth = val.formLabelWidth || "150px";
                    if (val.ground.id > 0) {
                        this.ground = val.ground;
                    }
                    if (val.userId && val.userId > 0) {
                        this.userId = val.userId;
                        this.ground.farmerId = val.userId;
                    }
                    this.loadData();
                }
            },
            visible(val) {
                if (!val) this.$emit("on-show-change", this.$data);
            }
        },
        mounted() {
            this.pollinationTreeTypes = this.codebooks ? this.codebooks.pollinationTreeTypes : [];
            this.ownTypes = this.codebooks ? this.codebooks.attributionTypes : [];
            //获取合作社
            this.$api.cooperative.all(result => {
                this.cooperatives = result.cooperatives;
            })
            this.areaChange('');
        },
        methods: {
            close() {
                this.cancle('groundForm');
            },
            cancle(formName) {
                this.$refs[formName].clearValidate();
                this.visible = false;
                this.ground = {
                    id: 0
                };
            },
            loadData() {
                if (!this.ground || !this.ground.id || this.ground.id <= 0) {
                    return;
                }
                this.$api.ground.detail(this.ground.id, result => {
                    this.ground = result.ground;
                    //防止该块土地没有pollinationType
                    this.ground.pollinationTreeType =
                        this.ground.pollinationTreeType && this.ground.pollinationTreeType.value != null
                            ? this.ground.pollinationTreeType.value : "";
                    this.ground.attributionType = this.ground.attributionType && this.ground.attributionType.value != null ? this.ground.attributionType.value : '';
                    if (this.ground.cooperativeId) {
                        this.cooperativeChange(this.ground.cooperativeId);
                    }
                    if (this.ground.provinceCode && this.ground.cityCode && this.ground.countyCode && this.ground.townCode && this.ground.villageCode) {
                        this.area = [this.ground.provinceCode, this.ground.cityCode, this.ground.countyCode, this.ground.townCode, this.ground.villageCode];
                        this.loadSaveArea(this.area, this.area.length);
                    }
                    this.$delete(this.ground, 'status');
                });
            },
            cooperativeChange(val) {
                this.$api.cooperative.farmers(val, result => {
                    this.farmers = result.farmers;
                })
            },
            submit(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        const callback = () => {
                            this.cancle(formName);
                        };
                        this.cooperatives.forEach(item => {
                            if (item.id == this.ground.cooperativeId) {
                                this.ground.cooperativeName = item.name;
                            }
                        })
                        this.ground.provinceCode = this.area[0];
                        this.ground.cityCode = this.area[1];
                        this.ground.countyCode = this.area[2];
                        this.ground.townCode = this.area[3];
                        this.ground.villageCode = this.area[4];
                        this.ground.id
                            ? this.$api.ground.update(this.ground, callback)
                            : this.$api.ground.save(this.ground, callback);
                    } else {
                        return false;
                    }
                });
            },
            areaChange(val) {
                let parentCode = '';
                if (val) {
                    parentCode = val[val.length - 1];
                } else {
                    parentCode = val;
                }
                this.$api.common.getAreaByParentCode(parentCode, result => {
                    if (!val) {
                        this.areas = result.areas;
                    } else {
                        result.areas = result.areas.map(item => {
                            if (item.areaLevel.value === "VILLAGE") {
                                return {
                                    value: item.value,
                                    label: item.label,
                                    parentCode: item.parentCode,
                                    areaLevel: item.areaLevel
                                }
                            } else {
                                return item;
                            }
                        })
                        this.pickChild(this.areas, parentCode, result.areas, val.length);
                    }
                })
            },
            pickChild(orgArea, parentCode, childArea, deep) {
                if (orgArea) {
                    orgArea.forEach(item => {
                        if (item.value === parentCode && item.areaLevel.value != 'VILLAGE') {
                            item.children = childArea;
                        } else {
                            this.pickChild(item.children, parentCode, childArea, deep--);
                        }
                    });
                }
            },
            loadSaveArea(area, loop) {
                if (loop < 0) {
                    return;
                }
                let code = area[area.length - loop];
                this.$api.common.getAreaByParentCode(code, result => {
                    let child = result.areas.map(item => {
                        if (item.areaLevel.value === "VILLAGE") {
                            return {
                                value: item.value,
                                label: item.label,
                                parentCode: item.parentCode,
                                areaLevel: item.areaLevel,
                            }
                        } else {
                            return item;
                        }
                    });

                    this.pickChild(
                        this.areas,
                        code,
                        child,
                        area - loop
                    );
                    loop--;
                    if (loop === 0) {
                        return;
                    }
                    this.loadSaveArea(area, loop);
                });
            }
        },
        props: {
            value: {
                type: Object,
                default: function () {
                    return {
                        show: false,
                        formLabelWidth: "150px",
                        ground: {
                            id: 0
                        }
                    };
                }
            }
        }
    };
</script>
